
#include "Lib.h"

#ifndef _UNIX

#include <Windows.h>

// #define OUT_TO_SCREEN

// timing

long long GetTickFrequency()
{
	static long long freq = 0;
	if (freq == 0)
	{
		LARGE_INTEGER li;
		::QueryPerformanceFrequency(&li);
		freq = li.QuadPart;
	}
	return freq;
}

static long long mFreq = GetTickFrequency();

double GetTimeSec()
{
	LARGE_INTEGER li;
	::QueryPerformanceCounter(&li);
	return ((double)li.QuadPart) / mFreq;
}

#endif

Logger* Logger::CreateLogger(const char* filename)
{
	FILE* fout = fopen(filename, "w");
	if (fout == NULL)
		return NULL;
	Logger* log = new Logger();
	log->fout = fout;
	log->isEvent = true;
	return log;
}

void Logger::BeginRecord(const char* fmt, ...)
{
	va_list args;
	va_start(args, fmt);

	double tm = GetTimeSec();

#ifdef OUT_TO_SCREEN
	printf("%.10lf,", tm);
	vprintf(fmt, args);
#endif

	fprintf(fout, "%.10lf,", tm);
	vfprintf(fout, fmt, args);

	va_end(args);

	isEvent = true;
}

void Logger::Record(const char* fmt, ...)
{
	assert(isEvent);

	va_list args;
	va_start(args, fmt);

#ifdef OUT_TO_SCREEN
	vprintf(fmt, args);
#endif
	vfprintf(fout, fmt, args);

	va_end(args);
}

void Logger::EndRecord()
{
#ifdef OUT_TO_SCREEN
	printf("\n");
#endif
	fprintf(fout, "\n");

	isEvent = false;
}

Logger::~Logger()
{
	fclose(fout);
}

//void CheckError(int error, const char* msg)
//{
//	if (error != JVMTI_ERROR_NONE)
//	{
//		printf("[Agent] ERROR: can't %s, error code: %d\n", msg, error);
//		exit(-1);
//	}
//}
